//
//  ST_MatchedMomentsController.swift
//  btvideo
//
//  Created by mac on 2020/1/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MJRefresh

//首页_配对 匹配person 朋友圈 -Controller 【弃用】
class ST_MatchedMomentsController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.white

         
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(emptyView.figured_height)
            make.centerY.equalToSuperview().offset( iPhoneXSeries ? -70 : -80)
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        self.request_data()
      
        
        
//        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: NSNotification.Name.init(ReceivedMatchNotificationKey), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.network_reachability_status, object: nil)
        
   }
   
   @objc func clear_data(){
        currentPage = 0
       self.data_array.removeAll()
       self.collectionView.reloadData()
   }
    fileprivate var currentPage = 0
    
    @objc fileprivate func refresh_data(){
        
        self.clear_data()
        self.request_data()
    }
    
    @objc fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage] as [String : Any]
        
        JVrequest(PH.matchedMomentsApi,parameters:param, success: { (json) in
            
            print("已经匹配人的Moments列表:",json)
            
            let dataStr = json["data"].rawString() ?? ""
            
            if let aArray = [ST_BTMomentsModel].deserialize(from: dataStr) as? [ST_BTMomentsModel]{
                
                
                
                if self.currentPage == 1{
                    self.data_array = aArray.map({ (m) -> ST_BTMomentsModel in
                        m.figure_out_cell_height()
                        return m
                    })
                    
                }else{
                    self.data_array += aArray.map({ (m) -> ST_BTMomentsModel in
                        m.figure_out_cell_height()
                        return m
                    })
                }
                
                self.collectionView.reloadData()
                
                
                self.load_more_option_style(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
                    
                    self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
                
            }else{
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                self.data_array.removeAll()
                self.collectionView.reloadData()
            }
            
            self.emptyView.isHidden = self.data_array.count > 0
            self.collectionView.isHidden = self.data_array.count < 1
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }

    //     MARK: - Properties


   fileprivate lazy var layout:UICollectionViewFlowLayout = {
      let controlLayout = UICollectionViewFlowLayout()
       controlLayout.minimumLineSpacing = 10
       controlLayout.minimumInteritemSpacing = 10
       controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: BTSafeAreaBottom + 49, right: 10)
        let w = ScreenWidth - 20
        let h = (ScreenWidth - 40)/335.0*300 + 80 + 50
        controlLayout.itemSize = CGSize.init(width: w, height: h)
       return controlLayout
   }()
   
   fileprivate lazy var collectionView:UICollectionView = {
       let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
       control.delegate = self
       control.dataSource = self
       control.register(cellWithClass: ST_BTMomentsCell.self)
       if #available(iOS 11.0, *) {
           control.contentInsetAdjustmentBehavior = .never
       }
       control.backgroundColor = Color.init(hexString: "#F5F8FA")
       
       control.alwaysBounceVertical = true
       control.showsVerticalScrollIndicator = false
       control.showsHorizontalScrollIndicator = false
       return control
   }()
    
    
    fileprivate lazy var emptyView:ST_BTEmptyView = {
        
        let control = ST_BTEmptyView.init(title: "有了特质才有对象。", imageName: ST_ImageUtils.imageName("首页_img_配对(空)")!, btnTitle: "添加特质") {
            
            
            push_to_push_peculiarity_controller(navigationController: self.navigationController)
        }
        control.isHidden = true
        return control
    }()
    
    fileprivate var data_array = [ST_BTMomentsModel]()

}

extension ST_MatchedMomentsController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    
    // MARK: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_BTMomentsCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.item]
        
        cell.unpair = { [weak self] id in
            
            self?.data_array.removeFirst { (m) -> Bool in
                return m.accid == id
            }
            
            self?.collectionView.reloadData()
        }
        
        cell.ignore_somebody_closure = { [weak self] id , str in
            self?.ignore(userId: id, notice: str)
        }
        
        return cell
    }

    // MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let h = data_array[indexPath.item].cellHeight
        
        return CGSize.init(width: ScreenWidth - 20, height: h)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        /*
        let vc = ST_SinglePeculiarityWaterfallController()
        vc.userID = data_array[indexPath.item].accid
        vc.peculiarity_id = data_array[indexPath.item].feature_id.string
        navigationController?.pushViewController(vc)
        */
        
        
        let item = data_array[indexPath.item]
        
        
        let vc = ST_PeculiarityGroupViewController.init(accid: item.accid, groupId: item.group_id.string, peculiarity_id: item.feature_id.string, firstPhotoSize: CGSize.init(width: item.width, height: item.height), remark: "")
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav, animated: true)
        
    }
    
}


//MARK: - Event
extension ST_MatchedMomentsController{
    
    func ignore(userId:String,notice:String){
        
        IgnoreBehavior(userId: userId) { (f, err) in
            
            if f{
                
              ToastHud(text: notice, view: self.view)
               
               main_thread_execute(afterDelay: 1.6) {
                   
                   self.data_array.removeFirst { (m) -> Bool in
                       return m.accid == userId
                   }
                   
                   self.collectionView.reloadData()
               }
                
            }else{
                self.toast(text: err)
            }
            
        }
        
    }
    
}
